package com.mi.shiro;


import com.mi.entity.AdminEntity;
import com.mi.entity.AuthInfo;
import com.mi.mapper.AdminMapper;
import com.mi.mapper.AuthMapper;
import com.mi.service.AuthService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Set;

public class MyRealm extends AuthorizingRealm {

    @Autowired
    AdminMapper adminMapper;

    @Autowired
    AuthMapper authMapper;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        Set<String> strings = authMapper.queryAuths(principalCollection.toString());
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.addStringPermissions(strings);
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken user = (UsernamePasswordToken)authenticationToken;
        AdminEntity adminEntity = new AdminEntity();
        adminEntity.setAccount(user.getUsername());
        AdminEntity login = adminMapper.login(adminEntity);
        if(login==null){
            throw new UnknownAccountException();
        }
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user.getPrincipal(), login.getApass(), this.getName());
        return simpleAuthenticationInfo;
    }
}
